import {request} from "../../util/request.js";

const url = "https://w7test.kuyuan.vip/app/index.php?i=2&c=entry&do=cloud&m=kuyuan_cloud";
const wx_appid = window.sysinfo.account.key;
const timestamp = parseInt(new Date().getTime()/1000);
const module_name = "kuyuan_fm";
let identity = "";  //验证码
let authority = "";  //授权码

/**
 * 获取云服务信息
 * @param module 模块标识
 */
let getCloud = function(){
    return new Promise((success)=>{
        request("cloud/getCloud",{
            module:module_name,
            wx_appid
        })
            .then((res)=>{
                if(res.data.status === "success"){
                    success(res.data.data);
                }else{
                    success(false);
                }
            });
    });
}

/**
 * 获取远程云服务信息
 */
let getRemoteCloud = function(identity,authority){
    return new Promise((success)=>{
        request("cloud/checkCloud",{
            identity,
            module:module_name,
            authority
        },url)
            .then((res)=>{
                if(res.data.status === "success"){
                    success(true);
                }else{
                    success(false);
                }
            });
    });
}

/**
 * 设置本地授权码信息
 */
let setLocalCloud = function(data){
    return new Promise((success)=>{
        request("cloud/setAuthority",data)
            .then((res)=>{
                if(res.data.status === "success"){
                    success();
                }
            });
    });
}

/**
 * 更新授权
 */
const update = function(){
    getCloud()
        .then((data)=>{
            identity = data.identity;
            authority = data.authority;
            if(timestamp > parseInt(data.check_time)){
                if(data.authority !== ""){
                    return getRemoteCloud(identity,authority);
                }
            }
        })
        .then((res)=>{
            if(res !== undefined){
                let data = {
                    identity,
                    check_time:timestamp + 86400
                }
                if(!res){
                    data.authority = "";
                }
                setLocalCloud(data);
            }
        })
}

/**
 * 验证授权是否设置或者已过期
 */
const check = function(){
    return new Promise((success)=>{
        getCloud()
            .then((data)=>{
                if(data.authority){
                    success(true);
                }else{
                    success(false);
                }
            });
    });
}


export {update,check};